<template>
  <div class="order-detail-container">
    <div class="order-header">
      <h2>订单详情</h2>
      <el-tag :type="getStatusTagType(order.status)" class="status-tag">
        {{ getStatusText(order.status) }}
      </el-tag>
      <div v-if="order.status === 1" class="countdown">
        剩余支付时间: {{ formatCountdown(order.remainingTime) }}
      </div>
    </div>

    <div class="order-info">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>订单信息</span>
        </div>
        <div class="info-item">
          <span class="label">订单编号:</span>
          <span class="value">{{ order.orderNo }}</span>
        </div>
        <div class="info-item">
          <span class="label">下单时间:</span>
          <span class="value">{{ formatDate(order.orderTime) }}</span>
        </div>
        <div v-if="order.payTime" class="info-item">
          <span class="label">支付时间:</span>
          <span class="value">{{ formatDate(order.payTime) }}</span>
        </div>
        <div class="info-item">
          <span class="label">订单状态:</span>
          <span class="value">{{ getStatusText(order.status) }}</span>
        </div>
        <div class="info-item">
          <span class="label">总金额:</span>
          <span class="value price">¥{{ order.totalPrice.toFixed(2) }}</span>
        </div>
        <div v-if="order.alipayNo" class="info-item">
          <span class="label">支付凭证:</span>
          <span class="value">{{ order.alipayNo }}</span>
        </div>
      </el-card>
    </div>

    <div class="ticket-info">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>票务信息</span>
        </div>
        <div class="ticket-content">
          <div class="ticket-cover">
            <img :src="order.ticket.concert.coverImg" alt="演唱会封面">
          </div>
          <div class="ticket-detail">
            <h3>{{ order.ticket.concert.name }}</h3>
            <div class="detail-item">
              <span class="label">艺人:</span>
              <span class="value">{{ order.ticket.concert.artist }}</span>
            </div>
            <div class="detail-item">
              <span class="label">场馆:</span>
              <span class="value">{{ order.ticket.concert.venue.name }}</span>
            </div>
            <div class="detail-item">
              <span class="label">地址:</span>
              <span class="value">{{ order.ticket.concert.venue.address }}</span>
            </div>
            <div class="detail-item">
              <span class="label">时间:</span>
              <span class="value">{{ order.ticket.concert.datetime }}</span>
            </div>
            <div class="detail-item">
              <span class="label">票价:</span>
              <span class="value">¥{{ order.ticket.price.toFixed(2) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">数量:</span>
              <span class="value">{{ order.ticketTotal }}张</span>
            </div>
            <div class="detail-item">
              <span class="label">座位等级:</span>
              <span class="value">{{ getTicketLevel(order.ticket.level) }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <div class="user-info">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>用户信息</span>
        </div>
        <div class="info-item">
          <span class="label">用户名:</span>
          <span class="value">{{ order.user.username }}</span>
        </div>
        <div class="info-item">
          <span class="label">手机号:</span>
          <span class="value">{{ order.user.phone }}</span>
        </div>
        <div class="info-item">
          <span class="label">邮箱:</span>
          <span class="value">{{ order.user.email }}</span>
        </div>
      </el-card>
    </div>

    <div class="action-buttons">
      <el-button
          v-if="order.status === 1"
          type="primary"
          @click="handlePay"
          class="pay-button">
        立即支付
      </el-button>
      <el-button
          v-if="order.status === 1"
          @click="handleCancel"
          class="cancel-button">
        取消订单
      </el-button>
      <el-button
          v-if="order.status === 3"
          type="primary"
          @click="handleRecreate"
          class="recreate-button">
        重新下单
      </el-button>
      <el-button @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "OrderDetail",
  data() {
    return {
      order: {
        orderNo: '',
        orderTime: '',
        payTime: '',
        userId: null,
        ticketId: null,
        totalPrice: 0,
        alipayNo: '',
        ticketTotal: 0,
        status: 0,
        isDeleted: 0,
        user: {
          username: '',
          phone: '',
          email: ''
        },
        ticket: {
          price: 0,
          level: 0,
          concert: {
            name: '',
            artist: '',
            coverImg: '',
            datetime: '',
            venue: {
              name: '',
              address: ''
            }
          }
        },
        remainingTime: 0
      },
      timer: null
    }
  },
  created() {
    this.loadOrderDetail()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    async loadOrderDetail() {
      const orderId = this.$route.query.id
      if (!orderId) {
        this.$message.error('订单不存在')
        this.$router.go(-1)
        return
      }

      try {
        const res = await this.request.get(`/user/order/${orderId}`)
        if (res.code === 200) {
          this.order = res.data
          // 如果订单未支付且还有剩余时间，启动倒计时
          if (this.order.status === 1 && this.order.remainingTime > 0) {
            this.startCountdown()
          }
        } else {
          this.$message.error(res.msg || '获取订单详情失败')
          this.$router.go(-1)
        }
      } catch (error) {
        this.$message.error('获取订单详情失败')
        this.$router.go(-1)
      }
    },

    startCountdown() {
      if (this.timer) {
        clearInterval(this.timer)
      }

      this.timer = setInterval(() => {
        if (this.order.remainingTime > 0) {
          this.order.remainingTime--
        } else {
          clearInterval(this.timer)
          // 订单超时，更新状态为已取消
          this.order.status = 3
        }
      }, 1000)
    },

    handlePay() {
      window.open(`http://localhost:9090/order/pay?subject=${this.order.ticket.concert.name}&traceNo=${this.order.orderNo}&totalAmount=${this.order.totalPrice}`)
    },

    async handleCancel() {
      try {
        const confirm = await this.$confirm('确定要取消该订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        if (confirm === 'confirm') {
          const res = await this.request.post('/user/order', {
            id: this.order.id,
            status: 3
          })

          if (res.code === 200) {
            this.$message.success('订单已取消')
            this.order.status = 3
            if (this.timer) {
              clearInterval(this.timer)
            }
          } else {
            this.$message.error(res.msg || '取消订单失败')
          }
        }
      } catch (error) {
        // 用户点击了取消
      }
    },

    handleRecreate() {
      this.$router.push(`/front/ticketDetail?id=${this.order.ticket.concert.id}`)
    },

    goBack() {
      this.$router.go(-1)
    },

    getStatusText(status) {
      switch (status) {
        case 1: return '待支付'
        case 2: return '已支付'
        case 3: return '已取消'
        default: return '未知状态'
      }
    },

    getStatusTagType(status) {
      switch (status) {
        case 1: return 'warning'
        case 2: return 'success'
        case 3: return 'info'
        default: return ''
      }
    },

    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleString()
    },

    formatCountdown(seconds) {
      if (!seconds) return '00:00'
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    },

    getTicketLevel(level) {
      switch (level) {
        case 1: return '普通座'
        case 2: return 'VIP座'
        case 3: return '贵宾座'
        default: return '未知等级'
      }
    }
  }
}
</script>

<style scoped>
.order-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.order-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.order-header h2 {
  margin-right: 20px;
  font-size: 24px;
  color: #333;
}

.status-tag {
  margin-right: 20px;
  font-size: 16px;
  padding: 8px 15px;
}

.countdown {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.box-card {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 15px;
  font-size: 16px;
}

.info-item .label {
  display: inline-block;
  width: 100px;
  color: #909399;
}

.info-item .value {
  color: #606266;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.ticket-content {
  display: flex;
}

.ticket-cover {
  width: 200px;
  margin-right: 30px;
}

.ticket-cover img {
  width: 100%;
  border-radius: 4px;
}

.ticket-detail {
  flex: 1;
}

.ticket-detail h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 20px;
  color: #333;
}

.detail-item {
  margin-bottom: 12px;
  font-size: 16px;
}

.detail-item .label {
  display: inline-block;
  width: 80px;
  color: #909399;
}

.detail-item .value {
  color: #606266;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}

.pay-button {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.pay-button:hover {
  background-color: #e05c5c;
  border-color: #e05c5c;
}

.cancel-button {
  margin-left: 20px;
}

.recreate-button {
  margin-left: 20px;
}
</style>